<template>
  <div style="width: 350px;">
    <el-form ref="ruleFormRef" :model="userForm" :rules="rules" label-width="120px" class="demo-ruleForm" :size="formSize"
      status-icon>
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="userForm.userName" />
      </el-form-item>
      <el-form-item label="密码" prop="userPwd">
        <el-input type="password" v-model="userForm.userPwd" show-password />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="userForm.gender" class="ml-4">
          <el-radio label='男' size="large">男</el-radio>
          <el-radio label='女' size="large">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          添加
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
    
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { ElNotification, type FormInstance, type FormRules } from 'element-plus'
import api from '@/api'

const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const userForm = ref({
  userName: '',
  userPwd: '',
  gender: '',
  roleId: 2
})

const rules = reactive<FormRules>({
  userName: [
    {
      required: true,
      message: '用户名不能为空',
      trigger: 'change',
    },
  ],
  userPwd: [
    {
      required: true,
      message: '密码不能为空',
      trigger: 'change',
    },
  ],
  gender: [
    {
      required: true,
      message: '性别不能为空',
      trigger: 'change',
    },
  ],
})


const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      api.user.addUser(userForm.value)
        .then(response => {
          // 在这里可以处理提交成功后的逻辑
          ElNotification({
            title: 'Success',
            message: response.data.msg,
            type: 'success',
            duration: 1500
          })
          formEl.resetFields()
        })
        .catch(error => {
          ElNotification({
            title: 'Error',
            message: error.data.msg,
            type: 'error',
            duration: 1500
          })
          // 在这里可以处理提交失败后的逻辑
        });
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

</script>
    